package cn.modfun.web.core.servlet;

import cn.modfun.common.lang.StringUtils;
import cn.modfun.web.core.annotation.Parameter.FilterMode;
import cn.modfun.web.core.annotation.Parameter.TrimMode;
import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;


public class ParameterHttpServletRequestWrapper extends HttpServletRequestWrapper {
	HttpServletRequest originalRequest = null;

	/**
	 * xss 策略 default 默认不做操作 repalce 替换 escape 转义 script 替换javascript脚本
	 */
	private Map<String, FilterMode> filterPolicy;
	/**
	 * trim 策略
	 */
	private Map<String, TrimMode> trimPolicy;

	public ParameterHttpServletRequestWrapper(HttpServletRequest request,Map<String, FilterMode> filterPolicy,Map<String, TrimMode> trimPolicy) {
		super(request);
		this.originalRequest = request;
		this.filterPolicy = filterPolicy;
		this.trimPolicy = trimPolicy;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String, String[]> getParameterMap() {

		HashMap<String, String[]> paramMap = new HashMap<String,String[]>();
		paramMap.putAll(super.getParameterMap());
		//paramMap = paramMap.clone();
		for (Iterator iterator = paramMap.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String, String[]> entry = (Entry<String, String[]>) iterator.next();
			String[] values = (String[]) entry.getValue();
			for (int i = 0; i < values.length; i++) {
				if (values[i] instanceof String) {
					values[i] = getValue(entry.getKey(),values[i]);
				}
			}
			entry.setValue(values);
		}
		return paramMap;
	}
	
	public String getValue(String name,String value){
		if(trimPolicy!=null && trimPolicy.get(name)!=null){
			if(TrimMode.All.equals(trimPolicy.get(name))){
				value = value.replaceAll("\\s*", "");
			}else if(TrimMode.Blank.equals(trimPolicy.get(name))){
				value = value.replaceAll(" +", "");
			}else if(TrimMode.Lr.equals(trimPolicy.get(name))){
				value = value.trim(); 
			}else if(TrimMode.L.equals(trimPolicy.get(name))){
				value = StringUtils.leftTrim(value);
			}else if(TrimMode.R.equals(trimPolicy.get(name))){
				value = StringUtils.rightTrim(value);
			}
		}
		if(filterPolicy!=null && filterPolicy.get(name)!=null){
			if(FilterMode.Replace.equals(filterPolicy.get(name))){
				value = replaceXSS(value);
			}else if(FilterMode.Escape.equals(filterPolicy.get(name))){
				value = StringEscapeUtils.escapeHtml3(value);
			}else if(FilterMode.Script.equals(filterPolicy.get(name))){
				value = scriptXSS(value);
			}
		}
		return value;
	}
	

	public String[] getParameterValues(String parameter) {
		String[] values = super.getParameterValues(parameter);
		if (values == null) {
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = getValue(parameter,values[i]);
		}
		return encodedValues;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (value != null) {
			value = getValue(name,value);
		}
		return value;
	}

	/**
	 * 将容易引起xss漏洞的半角字符直接替换成全角字符
	 * 
	 * @param s
	 * @return
	 */
	private String replaceXSS(String s) {
		if (s == null || "".equals(s)) {  
            return s;  
        }  
        StringBuilder sb = new StringBuilder(s.length() + 16);  
        for (int i = 0; i < s.length(); i++) {  
            char c = s.charAt(i);  
            switch (c) {  
            case '>':  
                sb.append('＞');//全角大于号  
                break;  
            case '<':  
                sb.append('＜');//全角小于号  
                break;  
            case '\'':  
                sb.append('‘');//全角单引号  
                break;  
            case '\"':  
                sb.append('“');//全角双引号  
                break;  
            case '&':  
                sb.append('＆');//全角  
                break;  
            case '\\':  
                sb.append('＼');//全角斜线  
                break;  
            case '#':  
                sb.append('＃');//全角井号  
                break;  
            default:  
                sb.append(c);  
                break;  
            }  
        }  
        return sb.toString();  
	}
	
	private String scriptXSS(String value) {
		if (value != null) {
			// NOTE: It's highly recommended to use the ESAPI library and
			// uncomment the following line to
			// avoid encoded attacks.
			// value = encoder.canonicalize(value);
			value = value.replaceAll("\0", "");

			// Avoid anything between script tags
			Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>",
					Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid anything in a src='...' type of expression
			scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");

			scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");

			// Remove any lonesome </script> tag
			scriptPattern = Pattern.compile("</script>",
					Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");

			// Remove any lonesome <script ...> tag
			scriptPattern = Pattern.compile("<script(.*?)>",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid eval(...) expressions
			scriptPattern = Pattern.compile("eval\\((.*?)\\)",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid expression(...) expressions
			scriptPattern = Pattern.compile("expression\\((.*?)\\)",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid javascript:... expressions
			scriptPattern = Pattern.compile("javascript:",
					Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid vbscript:... expressions
			scriptPattern = Pattern.compile("vbscript:",
					Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");

			// Avoid onload= expressions
			scriptPattern = Pattern.compile("onload(.*?)=",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
							| Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
		}
		return value;
	}

	/**
	 * 获取最原始的request
	 * 
	 * @return
	 */
	public HttpServletRequest getOriginalRequest() {
		return originalRequest;
	}

	/**
	 * 获取最原始的request的静态方法
	 * 
	 * @return
	 */
	public static HttpServletRequest getOriginalRequest(HttpServletRequest req) {
		if (req instanceof ParameterHttpServletRequestWrapper) {
			return ((ParameterHttpServletRequestWrapper) req).getOriginalRequest();
		}
		return req;
	}
}
